<template>
  <el-container class="home-container">
    <!-- 头部 -->
    <el-header>
      <HeaderComponent />
    </el-header>

    <!-- 主体内容 -->
    <el-main>
      <router-view />
    </el-main>

    <!-- 补充信息弹窗 -->
    <el-dialog
      title="请完善个人信息"
      :visible.sync="showUpdateDialog"
      :close-on-click-modal="false"
      :width="isMobile ? '90%' : '400px'"
      @closed="onUpdateDialogClosed"
    >
      <el-form label-position="top" label-width="80px">
        <el-form-item label="手机号">
          <el-input v-model="user.phone" placeholder="请输入手机号" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="submitUserInfo">提交</el-button>
      </div>
    </el-dialog>

    <!-- 账号激活弹窗 -->
    <el-dialog
      title="请激活账号"
      :visible.sync="showVerifyDialog"
      :close-on-click-modal="false"
      :show-close="false"
      :width="isMobile ? '90%' : '400px'"
    >
      <p>您的账号被冻结了，请输入验证码激活，验证码请咨询官方</p>
      <br>
      <el-input v-model="verifyCode" placeholder="请输入验证码" />
      <div slot="footer">
        <el-button type="primary" @click="submitVerifyCode">提交</el-button>
        <el-button type="primary" @click="logout">退出</el-button>
      </div>
    </el-dialog>
  </el-container>
</template>

<script>
import HeaderComponent from '@/components/HeaderComponent.vue';
import { mapState, mapMutations } from 'vuex';
import axios from 'axios';

export default {
  components: {
    HeaderComponent,
  },
  name: 'HomeView',
  data() {
    return {
      showUpdateDialog: false,
      showVerifyDialog: false,
      verifyCode: '',
      isMobile: window.innerWidth <= 768,
    };
  },
  computed: {
    ...mapState(['user']),
  },
  methods: {
    ...mapMutations(['setUser']),
    logout() {
      axios.get('/api/login/logout').catch(() => {})
      this.$router.push({ path: '/login' })
    },
    // 获取登录状态
    async checkLoginStatus() {
      try {
        const response = await axios.get('/api/login/user/checkLoginStatus');
        if (response.data.code == 1) {
          this.setUser(response.data.data);
        } else {
          this.$router.push({ path: '/login' });
        }
      } catch (error) {
        console.error('登录状态检查失败', error);
        this.$router.push({ path: '/login' });
      }
    },

    // 检查用户状态
    checkUserStatus() {
      if (!this.user.phone) {
        this.showUpdateDialog = true;
      }

      if (!this.user.active) {
        this.showVerifyDialog = true;
      }
    },

    // 提交用户信息
    async submitUserInfo() {
      if (!this.user.phone) {
        this.$message.warning('手机号不能为空');
        return;
      }

      try {
        const res = await axios.post('/api/user/updatePersonalInformationById', this.user);
        if (res.data.code == 1) {
          this.setUser(res.data.data); // 更新 Vuex
          this.showUpdateDialog = false;
          this.checkUserStatus(); // 再次检查是否还有其他弹窗要显示
        } else {
          this.$message.error('更新失败');
        }
      } catch (e) {
        console.error('更新用户信息失败', e);
        this.$message.error('网络错误');
      }
    },

    // 提交验证码
    async submitVerifyCode() {
      if (!this.verifyCode) {
        this.$message.warning('请输入验证码');
        return;
      }

      try {
        const res = await axios.post('/api/login/user/verify', { code: this.verifyCode });
        if (res.data.code == 1) {
          const updatedUser = { ...this.user, isActive: true };
          this.setUser(updatedUser);
          this.showVerifyDialog = false;
        } else {
          this.$message.error('验证码错误');
        }
      } catch (e) {
        console.error('验证码提交失败', e);
        this.$message.error('网络错误');
      }
    },

    // 弹窗关闭回调
    onUpdateDialogClosed() {
      if (!this.user.isActive) {
        this.showVerifyDialog = true;
      }
    },

    // 监听窗口大小变化（适配移动端）
    handleResize() {
      this.isMobile = window.innerWidth <= 768;
    },
  },
  mounted() {
    this.checkLoginStatus();
    window.addEventListener('resize', this.handleResize);
  },
  watch: {
    user: {
      deep: true,
      immediate: true,
      handler(newUser) {
        if (newUser && Object.keys(newUser).length > 0) {
          this.checkUserStatus();
        }
      },
    },
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
  },
};
</script>

<style scoped>
.home-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}

.el-header {
  padding: 1rem;
  background-color: white;
  border-bottom: 1px solid #ebeef5;
  flex-shrink: 0;
  margin: 0;
}

.el-main {
  flex-grow: 1;
  padding: 1rem;
  overflow-y: auto;
  margin: 0;
  background-color: white;
  display: flex;
  justify-content: center; /* 水平居中 */
}

</style>